var watchPayStatus = null;

var getInput = function(name){
  return $('[name='+name+']').val()
}

var setInput = function(name, value){
  $('[name='+name+']').val(value)
}
// 移除HTML标签
swig.setFilter('rmhtml', function (content) {
  var regex = /(<([^>]+)>)/ig;
  return content.replace(regex, '');
});

// 价格过滤器
swig.setFilter('priceFilter', function(input){
  return input ? (parseInt(input)/100).toFixed(2) : 0;
});

// 订单列表
(function () {
  
  ClientBridge.setMenus([])
  
  if (!/\/store\/orders/.test(location.pathname) 
    && !/\/store\/storeorders/.test(location.pathname) 
    && !/\/store\/todayorders/.test(location.pathname) 
    && !/\/store\/todayVendorOrders/.test(location.pathname) 
    && !/\/store\/ordersearch/.test(location.pathname)) {
    return false;
  }
  
  
  
  var loadUrl = '/store/ajax/orders/'

  if(/\/store\/storeorders/.test(location.pathname)){
    loadUrl = '/store/ajax/storeorders'
    /*
    ClientBridge.setMenus([{
      name: '筛选社区',
      content: '/store/projects'
    }]);
    */
  }
  else if(/\/store\/orders/.test(location.pathname) && $('body.orders').length){
    ClientBridge.setMenus([{
      name: '搜索订单',
      content: '/store/ordersearch'
    }]);
  }
  else if(/\/store\/todayorders/.test(location.pathname)){
    loadUrl = '/store/ajax/todayorders'
  }
  else if(/\/store\/todayVendorOrders/.test(location.pathname)){
    loadUrl = '/store/ajax/todayVendorOrders'
  }
  else if(/\/store\/ordersearch/.test(location.pathname)){
    loadUrl = '/store/ajax/ordersearch?keyWord='+getInput('keyWord')
  }


  // 更多订单
  loadMoreFactory({
    size: 10,
    url: loadUrl,
    panel: '#orders',
    template: '#ordersTempl'
  });
})();
// 菜单设置
$(function(){
  if($('body.checkout').length){
    ClientBridge.setMenus([{
      name: '历史收款',
      content: '/store/payhistory'
    }]);
  }
})
// 清空搜索记录
$(function(){
  $('[data-role=clearKeywords]').on('click', function(e){
    $.get('/store/ajax/keywords/clear').then(function(){
      $('.keywords-block').remove()
    })
  })
})

// 店铺收款
$(function(){
  // 金额校对
  $('.checkout [name=price]').on('keyup blur', function(e){
    var newValue = $(this).val().replace(/[^(\d|\.)]/g,'')
    $(this).val(e.type == 'keyup' ? newValue : (newValue ? parseFloat(newValue).toFixed(2) : ''))
  })

  $('.checkout .pay-form').on('submit', function(e){
    
    if(!getInput('price')){
      notice('请输入收款金额')
      e.preventDefault()
    }
  })  
})

// 发货
$(function(){
  var validForm = function(){
    var valid = false
    switch(getInput('deliverType')){
      case 'delivery':
        if(!getInput('deliverName')){
          notice('请输入配送员姓名')
        }else if(!/^\d{11}$/.test(getInput('deliverMobile'))){
          notice('请输入正确的手机号')
        }else{
          valid = true
        }
        break;
      case 'sendout':
        if(!getInput('logisticsCode')){
          notice('请输入快递单号')
        }else if(!getInput('logisticsName')){
          notice('请输入快递公司')
        }else{
          valid = true
        }
        break;
    }
    
    return valid
  }

  $('body.delivery').on('click','button',function(e){
    var name = $(this).attr('name')
    switch(name){
      case 'delivery':
      case 'sendout':
        $(this).removeClass('light').siblings('button').addClass('light')
        $('.'+name+'-block').show().siblings('.list').hide()
        setInput('deliverType', name)
        break;
      case 'saveBtn':
        if(validForm()){
          var text_1,text_2;
          if(getInput('deliverType') == 'delivery'){
            text_1 = '配送员姓名：'+ getInput('deliverName')
            text_2 = '配送员手机号：'+getInput('deliverMobile')
          }else{
            text_1 = '快递单号：'+ getInput('logisticsCode')
            text_2 = '快递公司：'+getInput('logisticsName')
          }
          Modal.confirm({
            message: Template.compile('#logisMsgTempl', {
              v1: text_1,
              v2: text_2
            }),
            callback: function () {
              $('form[name=deliveryForm]').submit()
            }
          });
          
        }
        break;
      default:
        break;
    }
  })
})

// 订单收款
$(function(){
  $('.cashier .get-pay-btn').on('click', function(e){
    switch($(':checked[name=payType]').val()){
      case 'qrcode':
        location.href = '/store/cashier/paycode/' + ($(this).data('ordercode') || 'NG07500011603071627000292')
        break;
      case 'cash':
        var _shouldPay = $(this).data('shouldpay'),
            _orderCode = $(this).data('ordercode');
        Modal.confirm({
          message: Template.compile('#payTempl', {shouldPay: _shouldPay}),
          callback: function () {
            $.get('/store/cashCollectFees', {
              orderCode: _orderCode
            }).then(function(res){
              if(res.code === 200){
                location.href = '/store/payordersuccess?shouldPay='+_shouldPay+'&orderCode='+_orderCode+'&payType=现金'
              }else{
                notice(res.data.message)
              }
            })
          }
        });
        break;
      default:
        break;

    }
  })  
})



// 监听店铺收款二维码支付状态
$(function(){
  if($('.pay-code').length){
    var getPayStatus = function(){
      $.get('/store/ajax/paystatus/'+getInput('qrCodeId')).then(function(res){
        if(res.data.entity){
          // 支付成功了
          clearInterval(watchPayStatus)
          location.href = '/store/paysuccess/' + getInput('qrCodeId')
        }
      }, function(rej){

      })
    }
    watchPayStatus = setInterval(getPayStatus, 3000)
  }
})

// 监听订单收款二维码支付状态
$(function(){
  if($('.order-pay-code').length){
    var getPayStatus = function(){
      $.get('/store/ajax/bepaid/'+getInput('orderCode')).then(function(res){
        // 支付成功了
        var data = res.data
        if(data.pay){
          clearInterval(watchPayStatus)
          location.href = '/store/payordersuccess?orderCode='+data.orderCode+'&shouldPay='+data.shouldPay+'&payType='+data.payType
        }
      }, function(rej){

      })
    }
    watchPayStatus = setInterval(getPayStatus, 3000)
  }
})

// 收款成功到首页
$(function(){
  $('#goHome').on('click', function(e){
    window.WebViewJavascriptBridge && window.WebViewJavascriptBridge.callHandler('jsToolCloseWebPage')
  })
})

// 订单历史
$(function(){
  if(!/\/store\/payhistory/.test(location.pathname)){
    return false
  }

  // 更多订单
  loadMoreFactory({
    size: 20,
    url: '/store/ajax/payhistory',
    panel: '#payHistory',
    template: '#historyTempl'
  });
})





